<?php

class RequestController extends Zend_Controller_Action
{

    protected $_namespace = 'RequestController';

    /**
     *
     * @var Zend_Session_Namespace
     */
    protected $_session;

    public function init()
    {
	$this->_helper->acl->allow('admin')
		->allow('user', array('index', 'list'));
	$this->_session = new Zend_Session_Namespace($this->_namespace);
    }

    public function overviewAction()
    {
	$request = $this->getRequest();

	if ($request->isGet())
	{
	    $this->renderOverview();
	} else if ($request->isPost() && $request->getParam('create_request'))
	{
	    $this->processRequest();
	} else if ($request->isPost() && $request->getParam('abort_request'))
	{
	    $this->abortRequest();
	}
    }

    private function abortRequest()
    {
	$this->_session->unsetAll();
	$this->redirect('/');
    }

    private function processRequest()
    {
	if (!isset($this->_session->child))
	{
	    $this->redirect("/");
	}

	$events = $this->_session->events;
	$child = $this->_session->child;
	unset($child['age']);

	$results = array();

	array_push($results, array('info' => "Antrag für " . $child['forename'] . " " . $child['surname'] . " wurde angelegt"));

// Creation of child if it does not exist
	if (!isset($child['id']))
	{
	    $modelChild = new Model_Child;
	    $child['birthday'] = (new Zend_Date($child['birthday']))->toString(Zend_Date::ISO_8601);
	    $child['id'] = $modelChild->create($child);
	    array_push($results, array('info' => "Kind mit dem Namen " . $child['forename'] . " " . $child['surname'] . " wurde angelegt"));
	} else
	{
	    array_push($results, array('info' => "Kind mit dem Namen " . $child['forename'] . " " . $child['surname'] . " wurde ausgewählt"));
	}

// Attach the parents
	$modelParent = new Model_Parent;
	$modelAllocate = new Model_Allocate();
	foreach ($this->_session->parents as $parent)
	{
	    $parentId = isset($parent['parent']['id']) ? $parent['parent']['id'] : NULL;
	    if ($parentId == NULL)
	    {
// Parent does not exist
		array_push($results, array('info' => "Elternteil mit dem Namen " . $parent['parent']['forename'] . " " . $parent['parent']['surname'] . " wurde angelegt"));
		$parentId = $modelParent->create($parent['parent']);
	    }

	    $i = count($modelAllocate->findAllocation($child['id'], $parentId));
	    if ($i == 0)
	    {
		$modelAllocate->allocate_create(array(
		    'idperson1' => $child['id'],
		    'idperson2' => $parentId));
	    }
	}


// Array for the total created events
	$eventsToCreate = array();
	$eventsToCreate['once'] = array();
	$eventsToCreate['weekly'] = array();

// Event model for creating events
	$modelEvent = new Model_Event;

// Counts the weekly events for later series creation
	$weeklyCount = 0;



// Extract the single events out of the series and single dates
	foreach ($events as $event)
	{

	    if ($event['frequence'] == 'WEEKLY')
	    {

		$eventsToCreate['weekly'][$weeklyCount] = array();

		$eventDateFrom = new Zend_Date($event['date_from']);
		$eventDateTo = new Zend_Date($event['date_to']);
		$eventLastDate = new Zend_Date($event['last_date']);

		$dates = $modelEvent->listDatesBetween($eventDateFrom, $eventLastDate);

		foreach ($dates as $date) /* @var $date Zend_Date */
		{
		    $eventToAdd = $event;

		    $eventToAddDateFrom = clone $date;
		    $eventToAddDateTo = clone $date;

		    $eventToAddDateFrom->setTime($eventDateFrom->getTime());
		    $eventToAddDateTo->setTime($eventDateTo->getTime());

		    $eventToAdd['date_from'] = $eventToAddDateFrom->toString();
		    $eventToAdd['date_to'] = $eventToAddDateTo->toString();

		    array_push($eventsToCreate['weekly'][$weeklyCount], $eventToAdd);
		}

		$weeklyCount++;
	    } else
	    {
		array_push($eventsToCreate['once'], $event);
	    }
	}

	$modelEventLinkPerson = new Model_EventLinkPerson;

	foreach ($eventsToCreate['once'] as $event)
	{
	    $errors = array();
	    $event['event_status'] = $modelEvent->getAcceptedStatus($child, $event, $errors);
	    $personLinkEvent = array('idperson' => $child['id'], 'idevent' => $modelEvent->create($event));
	    $eventInfo = array(
		'errors' => $errors,
		'info' => "Einzeltermin vom Typ [" . $event['event_type'] . "] vom [" . $event['date_from'] . "] bis [" . $event['date_to'] . "] mit Status [" . $event['event_status'] . "] wurde angelegt.",
	    );
	    array_push($results, $eventInfo);
	    $modelEventLinkPerson->create($personLinkEvent);
	}

	$modelSeries = new Model_Series;
	foreach ($eventsToCreate['weekly'] as $eventSeries)
	{
	    $eventSeriesId = $modelSeries->create();
	    foreach ($eventSeries as $event)
	    {
		$errors = array();
		$event['event_status'] = $modelEvent->getAcceptedStatus($child, $event, $errors);
		$event['idevent_series'] = $eventSeriesId;
		$personLinkEvent = array('idperson' => $child['id'], 'idevent' => $modelEvent->create($event, true));
		$eventInfo = array(
		    'errors' => $errors,
		    'info' => "Einzeltermin vom Typ [" . $event['event_type'] . "] vom [" . $event['date_from'] . "] bis [" . $event['date_to'] . "] mit Status [" . $event['event_status'] . "] wurde angelegt.",
		);
		array_push($results, $eventInfo);
		$modelEventLinkPerson->create($personLinkEvent);
	    }
	}

	$this->_session->unsetAll();

	$this->view->results = $results;
	$this->render('result');
    }

    public function attachparentAction()
    {
	$request = $this->getRequest();
	$form = new Application_Form_AttachParent;
	$this->addButtons($form);
	$this->view->form = $form;
	$this->view->child = $this->_session->child;

	if ($request->isPost())
	{
	    if ($request->getParam('back') != NULL)
	    {
		$this->redirect('/request/overview');
	    }

	    if ($form->isValid($request->getParams()))
	    {

		$modelParent = new Model_Parent;
		$modelAddress = new Model_Address;

		$parent = $modelParent->find($request->getParam('parent_id'));
		$address = NULL;

		if ($parent['idaddress'] != NULL)
		{
		    $address = $modelAddress->find($parent['idaddress']);
		}

		array_push(
			$this->_session->parents, array(
		    'parent' => $parent,
		    'address' => $address
		));

		$this->redirect('/request/overview');
	    }
	}

	$this->render('attachparent');
    }

    private function addChildWithParentsByChildId($childId)
    {
	$modelChild = new Model_Child;
	$modelParent = new Model_Parent;
	$child = $modelChild->find($childId);

	$parents = $modelParent->listParentsOfChildWithId($childId);

// Remove existing parents 
	$this->_session->parents = array();

	foreach ($parents as $parent)
	{
	    array_push($this->_session->parents, array('parent' => $parent));
	}

	$this->_session->child = $child;
    }

    public function deleteparentAction()
    {
	$request = $this->getRequest();
	unset($this->_session->parents[$request->getParam('id')]);
	$this->redirect('/request/overview');
    }

    public function createparentAction()
    {
	$request = $this->getRequest();
	$form = new Zend_Form;
	$form->addSubForm(new Application_Form_Parent, 'parent');
	$form->addSubForm(new Application_Form_Address, 'address');
	$this->addButtons($form);
	$this->view->form = $form;

	if ($request->isPost())
	{
	    if ($request->getParam('back') != NULL)
	    {
		$this->redirect('/request/overview');
	    }

	    if ($form->isValid($request->getParams()))
	    {
		array_push(
			$this->_session->parents, array(
		    'parent' => $form->getSubForm('parent')->getValues(true),
		    'address' => $form->getSubForm('address')->getValues(true)));
		$this->redirect('/request/overview');
	    } else
	    {
		$form->populate($request->getParams());
	    }
	}
	$this->render('createparent');
    }

    public function selectchildAction()
    {
	$request = $this->getRequest();
	$form = new Application_Form_ChildSelect;
	$form->setAction('/request/selectChild');
	$this->addButtons($form);
	$this->view->form = $form;
	if ($request->isPost())
	{
	    if ($request->getParam('back') != NULL)
	    {
		$this->redirect('/request/start/choose_child/choose_child');
	    } else if ($request->getParam('forward') != NULL)
	    {
		if ($form->isValid($request->getParams()))
		{
		    $this->addChildWithParentsByChildId($request->getParam('child_id'));
		    $this->redirect('/request/overview');
		} else
		{
		    $form->populate($request->getParams());
		    $this->render('form');
		}
	    }
	} else
	{
	    $form->populate($request->getParams());
	    $this->render('form');
	}
    }

    public function removeeventAction()
    {
	$idToRemove = $this->getRequest()->getParam('id');


	if (isset($idToRemove))
	{
	    unset($this->_session->events[$idToRemove]);
	    $this->redirect('/request/overview');
	} else
	{
	    $this->notFound();
	}
    }

    public function addeventAction()
    {
	$request = $this->getRequest();
	$form = new Application_Form_Event;
	$form->setEventTypesToChildEvents();
	// Adds special caretime validator
	$form->addInCaretimeValidator();
	$form->removeElement('event_status');
	$form->removeElement('child_id');
	$form->removeElement('add_event');
	$this->addButtons($form);
	$this->view->form = $form;


	if ($request->isGet())
	{
	    $this->render('form');
	} else if ($request->isPost())
	{
	    if ($request->getParam('back') != NULL)
	    {
		$this->redirect('/request/overview');
	    } else
	    {
		if ($form->isValid($request->getParams()))
		{
		    $event = $form->getValues();
		    array_push($this->_session->events, $event);
		    $this->redirect('/request/overview');
		} else
		{
		    $frequence = $form->getValue('frequence');
		    if ($frequence == 'WEEKLY')
		    {
			$form->setLastDateVisible(true);
		    }
		    $this->view->form = $form;
		    $this->render('form');
		}
	    }
	}
    }

    private function initializeEmptyRequest()
    {
	$this->_session->unsetAll();
	$this->_session->parents = array();
	$this->_session->events = array();
    }

    public function startAction()
    {
	$form = new Application_Form_ChooseChild;
	$form->setAction('/request/start');
	$request = $this->getRequest();
	if ($request->isGet())
	{
	    $form->populate($request->getParams());
	    $this->view->form = $form;
	} else
	{
	    if ($form->isValid($request->getParams()))
	    {
		$childChoiceType = $request->getParam('choose_child');

		if ($childChoiceType === 'choose_child')
		{
		    $this->redirect('/request/selectChild');
		} else if ($childChoiceType === 'create_child')
		{
		    $this->redirect('/request/createchild');
		}
	    } else
	    {
		$form->populate($request->getParams());
		$this->view->form = $form;
	    }
	}
    }

    public function createchildAction()
    {
	$request = $this->getRequest();
	$form = new Application_Form_Child;
	$this->addButtons($form);
	$this->view->form = $form;

	if ($request->isGet())
	{
	    if (isset($this->_session->child))
	    {
		$form->populate($this->_session->child);
	    }
	    $this->render('createchild');
	} else if ($request->isPost())
	{
	    if ($request->getParam('back') != NULL)
	    {
		$this->redirect('/request/start/choose_child/create_child');
	    } else
	    {
		if ($form->isValid($request->getParams()))
		{
		    $child = $form->getValues();
		    $modelChild = new Model_Child;
		    $child['age'] = $modelChild->calcAge($child['birthday']);
//		    $date = new Zend_Date($child['birthday']);
//		    $child['birthday'] = $date->toString(Zend_Date::ISO_8601);
		    $this->_session->child = $child;
		    $this->redirect('/request/overview');
		} else
		{
		    $form->populate($request->getParams());
		    $this->render('createchild');
		}
	    }
	}
    }

    public function prepareAction()
    {
	$this->initializeEmptyRequest();
	$request = $this->getRequest();
	$childId = $request->getParam('child_id');
	if ($childId != null)
	{
	    $this->addChildWithParentsByChildId($childId);
	    $this->redirect('/request/overview');
	}
    }

    public function createAction()
    {
	$request = $this->getRequest();
	if ($request->isGet())
	{
	    $this->initializeEmptyRequest();
	    $this->_redirect('/request/start');
	}
    }

    /**
     * 
     * @param Zend_Form $form
     */
    private function addButtons($form)
    {
	$this->addBackButton($form)->addForwardButton($form);
	$form->addDisplayGroup(array(
	    $form->getElement('back'),
	    $form->getElement('forward')
		), 'buttons');
    }

    /**
     * 
     * @param Zend_Form $form
     */
    private function addBackButton($form)
    {
	$form->addElement('submit', 'back', array(
	    'label' => 'Zurück',
	));
	return $this;
    }

    /**
     * 
     * @param Zend_Form $form
     */
    private function addForwardButton($form)
    {
	$form->addElement('submit', 'forward', array(
	    'label' => 'Weiter'
	));
	return $this;
    }

    private function renderOverview()
    {
	$parents = array();
	foreach ($this->_session->parents as $parent)
	{
	    array_push($parents, $parent['parent']);
	}
	$this->view->parents = $parents;
	$this->view->events = $this->_session->events;
	$space = array();
	$this->view->child = $this->_session->child;
	$this->render('overview');
    }

    private function notFound()
    {
	$this->getResponse()->setHttpResponseCode(404);
	$this->render();
    }

}

